package com.lgl.scs.wx.controller;

import com.lgl.scs.base.controller.BaseController;
import com.lgl.scs.information.service.AddressService;
import com.lgl.scs.mobile.service.MServiceOrderService;
import com.lgl.scs.util.utils.ControllerUtil;
import com.lgl.scs.wx.service.WxServiceOrderService;
import com.lgl.scsapi.system.model.AppUser;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.system.model.ServiceOrder;
import com.lgl.scsapi.util.utils.BillNumberTool;
import com.lgl.scsapi.util.utils.Constants;
import com.lgl.scsapi.util.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 微信小程序订单controller
 */
@RestController
@RequestMapping(value="/wx/serviceOrder")
public class WxServiceOrderController extends BaseController{
	private Logger log = LoggerFactory.getLogger(WxServiceOrderController.class);
	@Resource(name="wxServiceOrderService")
	private WxServiceOrderService wxServiceOrderService;
	@Resource(name="mServiceOrderService")
	private MServiceOrderService mServiceOrderService;
    @Resource(name="addressService")
    private AddressService addressService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

	//请求移动端主页的服务订单数据,暂时不考虑从redis中取数据
	@RequestMapping(value="/pageOrder",produces="application/json;charset=UTF-8")
	public Object pageOrder() {
		PageData mIndexPd = this.getPageData();
		AppUser loginUser = getSessionAppUser();
		return ControllerUtil.pageOrder(loginUser,mIndexPd,addressService,mServiceOrderService);
	}
	//获取我发布的服务订单数据,暂时不考虑从redis中取数据
	@RequestMapping(value="/listIssueOrderByMe",produces="application/json;charset=UTF-8")
	public Object listIssueOrderByMe() {
		PageData mIndexPd = this.getPageData();
		//发布人删除的不显示
		mIndexPd.put("statusNotEquals", "3");
		return commonReturnData(mIndexPd,"userId");
	}
    //取消服务订单
    @RequestMapping(value="/cancelServiceOrder",produces="application/json;charset=UTF-8")
    public Object cancelServiceOrder() {
        PageData cancelPd = this.getPageData();
        try {
            AppUser cancelUser = getSessionAppUser();
            String cancelState = wxServiceOrderService.cancelServiceOrder(cancelUser,cancelPd);
            cancelPd.put("code",cancelState);
        } catch (Exception e) {
            cancelPd.put("code","6");
            log.error("取消服务订单出错：" + e.getMessage(),e);
        }
        return cancelPd;
    }
	//抢单人/发布人删除服务订单
	@RequestMapping(value="/deleteOrder",produces="application/json;charset=UTF-8")
	public String deleteOrder(){
		PageData deletePd = this.getPageData();
		AppUser appUser = getSessionAppUser();
		try {
            return mServiceOrderService.deleteServiceOrder(appUser,deletePd);
		} catch (Exception e) {
			log.error("删除订单失败了,deletePd=" + deletePd + ",appUser=" + appUser.toString(),e);
		}
		return "6";
	}
	//发布人完成服务订单操作
	@RequestMapping(value="/issuerDoneOrder",produces="application/json;charset=UTF-8")
	public Object issuerDoneOrder() {
		PageData pd = this.getPageData();
		try {
			AppUser appUser = this.getSessionAppUser();
			String issuerDoneStatus = mServiceOrderService.issuerDoneOrder(appUser.getUserId(),pd);
			pd.put("code", issuerDoneStatus);
		} catch (Exception e) {
			pd.clear();
			pd.put("code", "6");
			log.error(e.toString(),e);
		}
		pd.put("soStatus", "2");
		return pd;
	}
	//抢单人完成订单
	@RequestMapping(value="/robberDoneOrder",produces="application/json;charset=UTF-8")
	public Object robberDoneOrder() {
		PageData robberDonePd = this.getPageData();
		AppUser robUser = this.getSessionAppUser();
		try {
			String state = wxServiceOrderService.robberDoneOrder(robUser.getUserId(),robberDonePd);
			robberDonePd.put("code",state);
		} catch (Exception e) {
			robberDonePd.clear();
			robberDonePd.put("code", "6");
			log.error("微信小程序：抢单人完成订单操作失败：robberDonePd=" + robberDonePd + ",robUser=" + robUser.toString(), e);
		}
		robberDonePd.put("soStatus","4");
		return robberDonePd;
	}
	//保存服务订单
	@RequestMapping(value="/saveServiceOrder", produces="application/json;charset=UTF-8")
	public Object saveServiceOrder(ServiceOrder serviceOrder) {
		PageData resultMap = new PageData(2);
		if (serviceOrder == null){
            resultMap.put("status","5");
            return resultMap;
        }
		AppUser appUser = this.getSessionAppUser();
		boolean isSuccess = false;
		String soCityCode = serviceOrder.getSoCityCode(),serviceDate = serviceOrder.getSoServiceDate(),
        areaCode = serviceOrder.getSoAreaCode();
        if (!StringUtils.hasText(serviceOrder.getSoName()) || !StringUtils.hasText(serviceOrder.getSoPhone())) {
            resultMap.put("status","4");
            return resultMap;
        }
        if (!DateUtil.isValidDate(serviceDate)) {
            resultMap.put("status","2");
            return resultMap;
        }
        //获取城市编码
		if (!StringUtils.hasText(soCityCode)){
            soCityCode = ControllerUtil.getCityCodeByName(serviceOrder,addressService);
			//如果没获取到城市编码，则直接返回失败
			if (!StringUtils.hasText(soCityCode)){
                resultMap.put("status","3");
				return resultMap;
			}
            serviceOrder.setSoCityCode(soCityCode);
		}

        if (!StringUtils.hasText(areaCode)){
            areaCode = addressService.getAreaCodeByName(serviceOrder);
            serviceOrder.setSoAreaCode(areaCode);
        }
        serviceOrder.setSoUserId(appUser.getUserId());
        //serviceOrder.setSoHtmlPath(Constants.HTML_PATH.split("html/")[1]);
        //订单号目前的规则是：1位客户端来源(0，1：PC，2，3，4：微信，5，6，7：安卓，8，9：IOS)+月日+4位随机码
        String clientNo = serviceOrder.getSoBillNumber();
        String billNo = BillNumberTool.getBillNo(clientNo, stringRedisTemplate);
        serviceOrder.setSoBillNumber(clientNo + billNo);
        try {
            isSuccess = wxServiceOrderService.saveServiceOrder(serviceOrder);
        } catch (Exception e) {
            log.error("生成订单报错了,订单详情：" + serviceOrder.toString(), e);
            //如果错误信息中包含“UQ_ORDER_BILLNO”，则说明是单号重复了，重新生成单号
            if (e.getMessage().contains("UQ_ORDER_BILLNO")) {
                isSuccess = retrySaveOrder(clientNo, billNo, serviceOrder);
            }
        }
        resultMap.put("status",isSuccess ? "0" : "1");
		return resultMap;
	}

	/**
     * 重试保存订单
     * @param clientNo     客户编码
     * @param billNo       订单号
     * @param serviceOrder 订单对象
     * @return true：成功,false: 失败
     */
    private boolean retrySaveOrder(String clientNo, String billNo, ServiceOrder serviceOrder) {
        boolean isSuccess = true;
        switch (clientNo){
			case "5":
				clientNo = "6";
				break;
			case "6":
				clientNo = "7";
				break;
			case "7":
				clientNo = "5";
				break;
		}
        try {
            serviceOrder.setSoBillNumber(clientNo + billNo);
            isSuccess = wxServiceOrderService.saveServiceOrder(serviceOrder);
        } catch (Exception e) {
            log.error("重试保存订单报错了", e);
            //如果错误信息中包含“UQ_ORDER_BILLNO”，则说明是单号重复了，重新生成单号
            if (e.getMessage().contains("UQ_ORDER_BILLNO")) {
                serviceOrder.setSoBillNumber(clientNo + BillNumberTool.getBillNo(clientNo, stringRedisTemplate));
                isSuccess = wxServiceOrderService.saveServiceOrder(serviceOrder);
            }
        }
        return isSuccess;
    }

	//我的服务订单信息
	@RequestMapping(value="/myMakeMoney",produces="application/json;charset=UTF-8")
	public Object myMakeMoney() {
		PageData pd = new PageData(4);
		//取得用户名
		AppUser appUser = this.getSessionAppUser();
		String makeMoney = wxServiceOrderService.myMakeMoney(appUser.getUserId());
		pd.put("status", "0");
		pd.put("totalMakeMoney", makeMoney);
		return pd;
	}

	//获取我已抢的服务订单数据,暂时不考虑从redis中取数据
	@RequestMapping(value="/listRobOrderByMe",produces="application/json;charset=UTF-8")
	public Object listRobOrderByMe() {
		PageData robPd = this.getPageData();
		//抢单人删除的不显示
		robPd.put("statusNotEquals", "7");
		return commonReturnData(robPd,"getUserId");
	}
	//获取我已抢未完成的服务订单数据
	@RequestMapping(value="/listFinishOrderByMe",produces="application/json;charset=UTF-8")
	public Object listFinishOrderByMe() {
		PageData finishPd = this.getPageData();
		finishPd.put("soStatus", "1");
		return commonReturnData(finishPd,"getUserId");
	}
	//待我确认的服务订单数据
	@RequestMapping(value="/listWaitSureByMe",produces="application/json;charset=UTF-8")
	public Object listWaitSureByMe() {
		PageData finishPd = this.getPageData();
		finishPd.put("soStatus", "4");
        return commonReturnData(finishPd,"userId");
	}
	//待我评价的服务订单(我发布的)
	@RequestMapping(value="/listIssueWaitRate",produces="application/json;charset=UTF-8")
	public Object listIssueWaitRate() {
		PageData waitRatePd = this.getPageData();
		int[] statusArray = {2,7}, isCommentedArr = {0,3};
		waitRatePd.put("statusArray", statusArray);
		waitRatePd.put("isCommentedArr", isCommentedArr);
        return commonReturnData(waitRatePd,"userId");
	}
    //待我评价的服务订单(我抢的)
    @RequestMapping(value="/listRobWaitRate",produces="application/json;charset=UTF-8")
    public Object listRobWaitRate() {
        PageData waitRatePd = this.getPageData();
        int[] statusArray = {2,3}, isCommentedArr = {0,2};
        waitRatePd.put("statusArray", statusArray);
        waitRatePd.put("isCommentedArr", isCommentedArr);
        return commonReturnData(waitRatePd,"getUserId");
    }

    /**
     * 通用的返回查询数据对象
     * @param commonPd  通用参数
     * @param userIdParamKey  需要使用userId作为value的key集合
     * @return PageData：表示返回错误信息，PageInfo：表示返回正确的数据列表
     */
    private Object commonReturnData(PageData commonPd, String... userIdParamKey){
        AppUser loginUser = getSessionAppUser();
        if (loginUser == null){
            commonPd.clear();
            commonPd.put("status", Constants.NO_LOGIN_CODE);
            return commonPd;
        }
        if (userIdParamKey != null){
            for (String userIdKey : userIdParamKey){
                commonPd.put(userIdKey,loginUser.getUserId());
            }
        }
        return wxServiceOrderService.wxPageServiceOrder(commonPd);
    }
	//抢服务订单
	@RequestMapping(value="/robServiceOrder", produces="application/json;charset=UTF-8")
	public Object robServiceOrder() {
		PageData resultMap = this.getPageData();
		AppUser appUser = this.getSessionAppUser();
		try {
			resultMap = wxServiceOrderService.robServiceOrder(appUser,resultMap);
		}catch (Exception e){
			log.error("抢单失败，robUser=" + appUser.toString() + ",resultMap=" + resultMap,e);
			resultMap.clear();
			resultMap.put("status","1");
		}
		return resultMap;
	}
}